#!/bin/env python
#-*- coding: utf-8 -*-
#/usr/local/tools/new_spring_prd.py app_name 8080

import os,sys,subprocess,time
from pwd import getpwnam
from grp import getgrnam

APP_HOME = "/usr/local/software"
app_name = sys.argv[1]

app_dir = APP_HOME+ '/'+app_name

#app_jar_filename = "spring-boot-wg-1.0.0.release.jar"
app_jar_filename = app_name + '.jar'
#print("app_jar_filename",app_jar_filename)
app_jar = app_dir+ '/'+app_jar_filename
#app_port = '8383'
app_port=sys.argv[2]

def fun_run(comm):
    handle =subprocess.Popen(comm, shell=True,stdout=subprocess.PIPE)
    return handle.communicate()[0]


def new_dir(app_name):
    bak_dir = "/opt/bak/" + app_name
    if not os.path.exists(bak_dir):
        os.makedirs(bak_dir)
        print "created ",bak_dir
    chown(bak_dir,"tomcat","tomcat")
    app_dir = "/usr/local/software"+ "/"+app_name
    if not os.path.exists(app_dir):
        os.makedirs(app_dir)
        print "created",app_dir
    chown(app_dir,"tomcat","tomcat")

def new_conf(app_name):
    app_jar_basename = app_jar_filename.split(".jar")[0]
    conf_file = app_dir + "/" + app_jar_basename +".conf"
    app_ip_name = app_name
    IP = get_ip()
    print(IP)
    #print(conf_file)
    if not os.path.isfile(conf_file): 
        conf_content = '''JAVA_HOME="/usr/local/jdk8"'''
        f = open(conf_file,"w")
        f.write(conf_content)
        f.write("\n")
        f.close
        conf_base = '''JAVA_OPTS="-Xmx2048M -Xms300M -XX:PermSize=228M -XX:MaxPermSize=888M -Xss256K -XX:+DisableExplicitGC -XX:SurvivorRatio=1 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=0 -XX:+CMSClassUnloadingEnabled -XX:LargePageSizeInBytes=256M -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=80 -XX:SoftRefLRUPolicyMSPerMB=0 -XX:+UseCompressedOops -server -Dfile.encoding=UTF-8 -Druntime.env=prd -Dspring.config.location=classpath:/prd/application.yml -Dserver.port=app_port -javaagent:/usr/local/software/pinpoint-agent-1.5.2/pinpoint-bootstrap-1.5.2.jar -Dpinpoint.agentId=IP -Dpinpoint.applicationName=serv_name"'''
        conf_content = conf_base.replace('serv_name',app_name).replace('app_port',app_port).replace('IP',IP)
        f = open(conf_file,"a")
        f.write(conf_content)
        f.write("\n")
        f.close
    chown(conf_file,"tomcat","tomcat")


def new_jar():
    touch(app_jar)
    os.chmod(app_jar,0700)    
    chown(app_jar,"tomcat","tomcat")
    src=app_jar
    print (src)
    dst="/etc/init.d/"+ app_name
    print(dst)
    if not os.path.exists(dst):
        os.symlink(src,dst)
    app_pid_dir="/var/run"+'/'+app_name
    if not os.path.exists(app_pid_dir):
        os.makedirs(app_pid_dir)
        chown(app_pid_dir,"tomcat","tomcat")


def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)

def get_ip():
    cmd = "/sbin/ifconfig | grep 'inet addr' | grep -v 127.0.0.1 | awk '{print $2}' | awk -F ':' '{print $2}'"
    pip = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE)
    ip = pip.stdout.read().split()[0]
    sip=ip[8:]
    return sip

def touch_var_log():
    log_file="/var/log/"+app_name+".log"
    touch(log_file)
    chown(log_file,"tomcat","tomcat")    
    print log_file,"touched"

def chown(path,uname,gname):
    uid = getpwnam(uname).pw_uid
    gid = getgrnam(gname).gr_gid
    #print(uid)
    os.chown(path, uid, gid)


if __name__=="__main__":
    #print len(sys.argv)
    if len(sys.argv) == 3:
        new_dir(app_name)
        new_conf(app_name)
        new_jar()
        print app_name,"new OK"
	touch_var_log()
    else: 
        print "spring_new_prd.py app_name app_port"

